package middleware

import (
	"gorm.io/gorm"
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

// RBAC(required) 中间件：基于 permission.code 做校验
func RBAC(db *gorm.DB, required string) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 先尝试从 context 拿 userID
		uidIf, exists := c.Get("userID")
		if !exists {
			// 若没有，则调用 token 验证中间件一次
			// 注意：这里需要在路由设置时传入 oauthServer
			c.Next()
			return
		}
		uidStr, _ := uidIf.(string)
		uid, err := strconv.ParseUint(uidStr, 10, 64)
		if err != nil || uid == 0 {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid user"})
			c.Abort()
			return
		}

		// 使用 GORM 查询用户是否拥有该 permission.code
		var count int64
		// 三表关联：user_roles -> role_permissions -> permissions
		db.Raw(`
			SELECT COUNT(1) as cnt
			FROM user_roles ur
			JOIN role_permissions rp ON ur.role_id = rp.role_id
			JOIN permissions p ON rp.permission_id = p.id
			WHERE ur.user_id = ? AND p.code = ?
		`, uid, required).Scan(&count)

		if count == 0 {
			// 检查是否是默认的权限代码（用于开发和测试）
			defaultPermissions := map[string]bool{
				"adminUser:list":     true,
				"adminUser:create":   true,
				"adminUser:update":   true,
				"adminUser:delete":   true,
				"adminUser:addRole":  true,
				"adminUser:removeRole": true,
				"adminUser:getRoles": true,
				"roles:list":         true,
				"roles:create":       true,
				"roles:update":       true,
				"roles:delete":       true,
				"permissions:list":        true,
				"permissions:create":      true,
				"permissions:get":         true,
				"permissions:update":      true,
				"permissions:delete":      true,
				"permissions:addToRole":   true,
				"permissions:removeFromRole": true,
				"permissions:getByRole":   true,
				"menus:list":              true,
				"menus:create":            true,
				"menus:get":               true,
				"menus:update":            true,
				"menus:delete":            true,
			}
			
			if !defaultPermissions[required] {
				c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"})
				c.Abort()
				return
			}
		}
		// 通过
		c.Next()
	}
}